package com.tools.cleanmaster.functionpage;

import android.content.Context;
import android.content.SharedPreferences;
import android.os.SystemClock;
import android.text.TextUtils;

import com.tools.cleanmaster.CleanApplication;
import com.tools.cleanmaster.cpucool.CpuCoolManager;
import com.tools.cleanmaster.cpucool.CpuTempInfo;
import com.tools.cleanmaster.scenenew.BatteryInfoTracker;
import com.tools.cleanmaster.scenenew.BatterySharpDecHelper;
import com.tools.cleanmaster.scenenew.SceneConstants;
import com.tools.cleanmaster.scenenew.SceneToolkit;
import com.tools.cleanmaster.scenenew.SceneType;

import org.json.JSONException;
import org.json.JSONObject;

import java.util.LinkedList;

/**
 * CreatedXXX on 17/7/10.
 */

public class FunctionItemSharedPrefs {
    private static SharedPreferences sPrefs = null;
    private static final String PREFS_FILE = "function_item";
    private static final String JSON_ITEM_MEASURE_DURATION = "duration";
    private static final String JSON_CPU_COOL_THRESHOLD = "cool_threshold";
    private static final String JSON_BATTERY_SHARP_DESC = "battery_threshold";
    private static final String JSON_BATTERY_PERCENT = "battery_percent";
    private static final String JSON_BOOSTER_THRESHOLD = "booster_threshold";
    private static final int DEFAULT_CPU_COOL_THRESHOLD = 37;
    private static final int DEFAULT_BATTERY_SHARP_DESC_THRESHOLD = 1;
    private static final int DEFAULT_BATTERY_DURATION = 10;
    private static final int DEFAULT_BOOSTER_THRESHOLD = 60;
    private static final String FUNCTION_LAST_BOOSTER_TIME = "booster_time";
    private static final String IS_BATTERY_NORMAL = "battery_normal";
    public static final long MINUTE_MS = 1000L * 60;
    private static final String ITEM_OVER_TIME = "over";
    private static final String ITEM_LANDING_PAGE_HANDLING = "l_p_handing";
    private static final String ITEM_FUNCTION_PAGE_HANDLING = "f_p_handing";
    private static LinkedList<BatterySharpDecHelper.BatteryData> mBatteryDatas =
            new LinkedList<BatterySharpDecHelper.BatteryData>();

    private static SharedPreferences initSharedPreferences(Context context) {
        if (sPrefs == null) {
            sPrefs = context.getSharedPreferences(PREFS_FILE, Context.MODE_PRIVATE);
        }
        return sPrefs;
    }

    public static void parseDataPipeConfig(String body) {
        if (!TextUtils.isEmpty(body)) {
            try {
                JSONObject obj = new JSONObject(body);
                Context context = CleanApplication.getInstance();
                saveCpuCoolThreshold(context, obj.optInt(JSON_CPU_COOL_THRESHOLD, DEFAULT_CPU_COOL_THRESHOLD));
                saveBatterySharpDescThreshold(context, obj.optInt(JSON_BATTERY_SHARP_DESC,
                        DEFAULT_BATTERY_SHARP_DESC_THRESHOLD));
                saveBatterySharpDescDuration(context, obj.optInt(JSON_ITEM_MEASURE_DURATION, DEFAULT_BATTERY_DURATION));
                saveBoosterThreshold(context, obj.optInt(JSON_BOOSTER_THRESHOLD, DEFAULT_BOOSTER_THRESHOLD));
            } catch (JSONException e) {
                e.printStackTrace();
            }
        }
    }

    public static void batterySharpDec(BatteryInfoTracker.BatteryInfo newData) {
        boolean validFlag = false;
        int percent = newData.percent;
        if (mBatteryDatas.isEmpty()) {
            mBatteryDatas.add(new BatterySharpDecHelper.BatteryData(percent, SystemClock.elapsedRealtime()));
        } else if (percent != mBatteryDatas.getLast().percent) {
            long curTime = SystemClock.elapsedRealtime();

            int thresholdTime = getBatterySharpDescDuration(CleanApplication.getInstance());
            int thresholdPrecent = getBatterySharpDescThreshold(CleanApplication.getInstance());

            while (!mBatteryDatas.isEmpty()) {
                if (curTime - mBatteryDatas.getFirst().time > thresholdTime * SceneConstants.MINUTE_MS) {
                    mBatteryDatas.removeFirst();
                } else {
                    break;
                }
            }
            for (BatterySharpDecHelper.BatteryData data : mBatteryDatas) {
                if (data.percent - percent >= thresholdPrecent) {

                    mBatteryDatas.clear();
                    validFlag = true;
                    break;
                }
            }
            mBatteryDatas.add(new BatterySharpDecHelper.BatteryData(newData.percent, curTime));
        }
        saveBatteryPercent(CleanApplication.getInstance(), percent);
        setIsBatteryNormal(CleanApplication.getInstance(), !validFlag);
    }

    private static void saveCpuCoolThreshold(Context context, int threshold) {
        initSharedPreferences(context).edit().putInt(JSON_CPU_COOL_THRESHOLD, threshold).apply();
    }

    private static void saveBatterySharpDescThreshold(Context context, int threshold) {
        initSharedPreferences(context).edit().putInt(JSON_BATTERY_SHARP_DESC, threshold).apply();
    }

    private static void saveBatterySharpDescDuration(Context context, int duration) {
        initSharedPreferences(context).edit().putInt(JSON_ITEM_MEASURE_DURATION, duration).apply();
    }

    public static int getCpuCoolThreshold(Context context) {
        return initSharedPreferences(context).getInt(JSON_CPU_COOL_THRESHOLD, DEFAULT_CPU_COOL_THRESHOLD);
    }

    public static int getBatterySharpDescThreshold(Context context) {
        return initSharedPreferences(context).getInt(JSON_BATTERY_SHARP_DESC, DEFAULT_BATTERY_SHARP_DESC_THRESHOLD);
    }

    public static int getBatterySharpDescDuration(Context context) {
        return initSharedPreferences(context).getInt(JSON_ITEM_MEASURE_DURATION, DEFAULT_BATTERY_DURATION);
    }

    private static void saveBoosterThreshold(Context context, int threshold) {
        initSharedPreferences(context).edit().putInt(JSON_BOOSTER_THRESHOLD, threshold).apply();
    }

    public static int getBoosterThreshold(Context context) {
        return initSharedPreferences(context).getInt(JSON_BOOSTER_THRESHOLD, DEFAULT_BOOSTER_THRESHOLD);
    }

    private static long getLastBoosterTime(Context context) {
        return initSharedPreferences(context).getLong(FUNCTION_LAST_BOOSTER_TIME, 0);
    }

    public static void setLastBoosterTime(Context context) {
        initSharedPreferences(context).edit().putLong(FUNCTION_LAST_BOOSTER_TIME, System.currentTimeMillis()).apply();
    }

    private static boolean isInBoosterProtectTime(Context context) {
        return (System.currentTimeMillis() > getLastBoosterTime(context)) &&
                (System.currentTimeMillis() < getLastBoosterTime(context) + MINUTE_MS * 5);
    }


    public static void setIsBatteryNormal(Context context, boolean isNormal) {
        initSharedPreferences(context).edit().putBoolean(IS_BATTERY_NORMAL, isNormal).apply();
    }

    public static boolean getIsCpuNormal(Context context) {
        CpuTempInfo info = CpuCoolManager.getInstance().startGetCpuTempSync(false, true);
        return CpuCoolManager.getInstance().isInProtectTime() || info.getCpuTemp() < getCpuCoolThreshold(context);
    }

    private static boolean getIsBatteryNormal(Context context) {
        return initSharedPreferences(context).getBoolean(IS_BATTERY_NORMAL, false);
    }

    private static boolean getIsBoosterNormal(Context context) {
        return isInBoosterProtectTime(context) || getBoosterThreshold(context) > SceneToolkit.calcMemoryUsedPercent();
    }

    // 以下是对于小红点的保护策略方法
    public static void setItemOverLastShowTime(Context context, FunctionItem item) {
        initSharedPreferences(context).edit().putLong(ITEM_OVER_TIME + item.toString(),
                System.currentTimeMillis()).apply();
    }

    private static long getItemOverLastShowTime(Context context, FunctionItem item) {
        return initSharedPreferences(context).getLong(ITEM_OVER_TIME + item.toString(), 0);
    }

    public static void setFunctionItemOverHandingTime(Context context, FunctionItem item) {
        initSharedPreferences(context).edit().putLong(ITEM_FUNCTION_PAGE_HANDLING + item.toString(),
                System.currentTimeMillis()).apply();
    }

    private static long getFunctionItemOverHandingTime(Context context, FunctionItem item) {
        return initSharedPreferences(context).getLong(ITEM_FUNCTION_PAGE_HANDLING + item.toString(), 0);
    }

    private static void saveBatteryPercent(Context context, int threshold) {
        initSharedPreferences(context).edit().putInt(JSON_BATTERY_PERCENT, threshold).apply();
    }

    public static int getBatteryPercent(Context context) {
        return initSharedPreferences(context).getInt(JSON_BATTERY_PERCENT, 50);
    }

    // 保存通过场景化sdk点击的时间点
    public static void setLandingPageHandingTime(Context context, SceneType sceneType) {
        FunctionItem item = null;
        switch (sceneType) {
            case BAT_SHARPDEC:
                item = FunctionItem.BATTERYOVER;
                break;
            case CPU_COOLER:
                item = FunctionItem.CPUOVER;
                break;
            case BG_MEM_OVERLOAD:
                item = FunctionItem.BOOSTEROVER;
                break;
            default:
                break;
        }
        if (null != item) {
            initSharedPreferences(context).edit().putLong(ITEM_LANDING_PAGE_HANDLING + item.toString(),
                    System.currentTimeMillis()).apply();
        }
    }

    private static long getLandingPageHandingTime(Context context, FunctionItem item) {
        return initSharedPreferences(context).getLong(ITEM_LANDING_PAGE_HANDLING + item.toString(), 0);
    }

    public static boolean getFunctionItemNormal(Context context, FunctionItem item) {
        boolean isNormal = true;
        switch (item) {
            case CPUCOOL:
            case CPUOVER:
                isNormal = isFunctionItemNormal(context, FunctionItem.CPUOVER);
                break;
            case BOOSTER:
            case BOOSTEROVER:
                isNormal = isFunctionItemNormal(context, FunctionItem.BOOSTEROVER);
                break;
            case BATTERY:
            case BATTERYOVER:
                isNormal = isFunctionItemNormal(context, FunctionItem.BATTERYOVER);
                break;
            default:
                break;
        }
        return isNormal;
    }

    private static boolean isFunctionItemNormal(Context context, FunctionItem item) {
        Long currentTime = System.currentTimeMillis();
        Long lastShowTime = getItemOverLastShowTime(context, item);
        Long lastHandingTime = getLandingPageHandingTime(context, item);
        Long lastFunctionHandingTime = getFunctionItemOverHandingTime(context, item);

        if (currentTime < lastShowTime + MINUTE_MS * 5) {
            if (currentTime > lastFunctionHandingTime && lastFunctionHandingTime > lastShowTime) {
                return true;
            }
            return currentTime > lastHandingTime && lastHandingTime > lastShowTime;
        } else {
            if (item == FunctionItem.BOOSTEROVER) {
                return getIsBoosterNormal(context);
            } else if (item == FunctionItem.CPUOVER) {
                return getIsCpuNormal(context);
            } else if (item == FunctionItem.BATTERYOVER) {
                return getIsBatteryNormal(context);
            }
            return true;
        }
    }
}
